#include<iostream>
#include<unistd.h>
#include<cerrno>
#include<cstring>
#include <sys/types.h>
#include<string>
#include<sys/wait.h>
#include <sys/types.h>
#define SIZE 1024

void chilewrite(pid_t wfd)
{
  while(1)
  {
    std::string message="father I am your child process!";
    write(wfd,message.c_str(),message.size());
    sleep(2);
  }
}

void fathread(pid_t rfd)
{
    char buffer[SIZE];
    while(1)
    {
        int n=read(rfd,buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            std::cout<<buffer<<std::endl;
        }
        else if(n==0)
        {
            // 如果read的返回值是0，表示写端直接关闭了，我们读到了文件的结尾
            std::cout<<"写端关闭了"<<std::endl;
            break;
        }
        else
        {
            std::cerr<<"read err"<<std::endl;
            break;
        }
    }
}

int main()
{
    //创建管道
    int pipefd[2];
    int n=pipe(pipefd);
    if(n<0)
    {
        std::cerr<<"errno:"<<errno<<" errstring:"<<strerror(errno)<<std::endl;
        return 1;
    }
    //创建子进程
    pid_t id=fork();
    if(id==0)
    {
        //子进程
        std::cout<<"子进程准备就绪，准备写入数据了"<<std::endl;
        close(pipefd[0]);
        chilewrite(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }
    //父进程
    std::cout<<"父进程准备就绪，准备读取数据了"<<std::endl;
    close(pipefd[1]);
    fathread(pipefd[0]);
    close(pipefd[0]);

    //进程等待
    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
        std::cout << "wait child process done, exit sig: " << (status&0x7f) << std::endl;
        std::cout << "wait child process done, exit code(ign): " << ((status>>8)&0xFF) << std::endl;
    }
    return 0;
}